﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using AngleSharp.Dom;
using AngleSharp.Html.Parser;
using Tool;
using Core.Expansion;
using Tool.Web.HttpHelper;
using Core.Common.Monitor;
using System.Threading;
using Tool.Expansion;
using Tool.Common;
using PuppeteerSharp;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Linq;
using System.Data;
using System.Globalization;

namespace Test
{
	class Program
	{
		static void Main(string[] args)
		{
			//Console.WriteLine(Url.GetShortUrl("https://www.acgdmzy.com/#/book/latest"));
			//Console.WriteLine(TimeHelp.TimeStampToDate(1593844877));
			//Test().Wait();
			//GetTweets("wuyu_8512");
			WebClient webClient = new WebClient { Proxy = new WebProxy("192.168.1.101:2802") };
			webClient.Headers["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36 Edg/83.0.478.58";
			webClient.Headers["authorization"] = GetAuthorization(out string path);
			Console.WriteLine(path);
			//webClient.Headers["authorization"] = "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA";
			//var path = "-xfUfZsnR_zqjFd-IfrN5A";
			//webClient.Headers["x-guest-token"] = "1279741933749809158";
			GetToken(ref webClient);
			//var userId = GetUserID(ref webClient, path, "wuyu_8512");
			var userId = "1127722112444092416";
			var tweets = GetTweets(ref webClient, userId);
		}

		static async Task Test()
		{
			var browser = await Puppeteer.LaunchAsync(new LaunchOptions
			{
				Headless = true,
				ExecutablePath = @"F:\酷Q Pro\dev\com.acgdmzy.acg\chrome-win\chrome.exe",
				Args = new string[] { "--no-sandbox", "--proxy-server=192.168.1.101:2802" }
			});
			var page = await browser.NewPageAsync();
			await page.SetRequestInterceptionAsync(true);
			page.Request += Page_Request;
			await page.GoToAsync("https://twitter.com/wuyu_8512", null, new WaitUntilNavigation[] { WaitUntilNavigation.Networkidle0 });
			await page.SetViewportAsync(new ViewPortOptions
			{
				Width = 1080,
				Height = 1920
			});
			await page.ScreenshotAsync("3.jpg");
			await browser.CloseAsync();
		}

		private async static void Page_Request(object sender, RequestEventArgs e)
		{
			if (e.Request.Url.Contains("pbs.twimg.com"))
				await e.Request.AbortAsync();   //终止请求
			else
				await e.Request.ContinueAsync();//弹出
		}

		public static void GetTweets(string name)
		{
			WebClient webClient = new WebClient();
			webClient.Proxy = new WebProxy("192.168.1.101:2802");
			webClient.Headers["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36 Edg/83.0.478.58";
			string @string = Encoding.UTF8.GetString(webClient.DownloadData("https://twitter.com"));
			Regex regex = new Regex("web/main\\.(.*?)\\.js");
			string text = "https://abs.twimg.com/responsive-web/" + regex.Match(@string).Value;
			Console.WriteLine(text);
			string string2 = Encoding.UTF8.GetString(webClient.DownloadData(text));
			File.WriteAllText("main.js", string2);
			Regex regex2 = new Regex("s=\"(A.*?)\"");
			string value = "Bearer " + regex2.Match(string2).Groups[1].Value;
			Console.WriteLine(value);
			webClient.Headers["authorization"] = value;
			string value2 = JObject.Parse(Encoding.UTF8.GetString(webClient.UploadData("https://api.twitter.com/1.1/guest/activate.json", new byte[0])))["guest_token"].ToString();
			Console.WriteLine(value2);
			string value3 = new Regex("queryId:\"([a-zA-Z0-9-_]*?)\",operationName:\"UserByScreenName\"").Match(string2).Groups[1].Value;
			Console.WriteLine(value3);
			webClient.Headers["x-guest-token"] = value2;
			//https://api.twitter.com/graphql/-xfUfZsnR_zqjFd-IfrN5A/UserByScreenName?variables=%7B%22screen_name%22%3A%22wuyu_8512%22%2C%22withHighlightedLabel%22%3Atrue%7D
			string text2 = $"https://api.twitter.com/graphql/{value3}/UserByScreenName?variables=%7B%22screen_name%22%3A%22{name}%22%2C%22withHighlightedLabel%22%3Afalse%7D";
			Console.WriteLine(text2);
			webClient.Headers["authorization"] = value;
			JToken arg = JObject.Parse(Encoding.UTF8.GetString(webClient.DownloadData(text2)))["data"]["user"]["rest_id"];
			string address = $"https://api.twitter.com/2/timeline/profile/{arg}.json?tweet_mode=extended";
			string string3 = Encoding.UTF8.GetString(webClient.DownloadData(address));
			//Console.WriteLine(string3);
			var json = JObject.Parse(string3);
			foreach (var item in json["timeline"]["instructions"][0]["addEntries"]["entries"])
			{
				var entryId = item["entryId"].ToString();
				if (entryId.Contains("tweet"))
				{
					var id = item["sortIndex"].ToString();
					var tweet = json["globalObjects"]["tweets"][id] as JObject;
					Console.WriteLine("推文ID：" + id);
					var isRetweet = tweet.ContainsKey("retweeted_status_id_str");
					Console.WriteLine("是否为转推：" + isRetweet);
					if (isRetweet) Console.WriteLine(json["globalObjects"]["tweets"][tweet["retweeted_status_id_str"].ToString()]["full_text"]);
					else Console.WriteLine("内容：" + tweet["full_text"]);
				}
			}
		}

		static string GetAuthorization(out string path)
		{
			WebClient webClient = new WebClient();
			webClient.Proxy = new WebProxy("192.168.1.101:2802");
			string @string = string.Empty;
			try
			{
				@string = Encoding.UTF8.GetString(webClient.DownloadData("https://twitter.com/"));
			}
			catch (WebException)
			{
				throw;
			}
			Regex regex = new Regex("web/main\\.(.*?)\\.js");
			string text = "https://abs.twimg.com/responsive-web/" + regex.Match(@string).Value;
			string string2 = Encoding.UTF8.GetString(webClient.DownloadData(text));
			File.WriteAllText("main.js", string2);
			Regex regex2 = new Regex("s=\"(A.*?)\"");
			string value = "Bearer " + regex2.Match(string2).Groups[1].Value;
			path = new Regex("queryId:\"([a-zA-Z0-9-_]*?)\",operationName:\"UserByScreenName\"").Match(string2).Groups[1].Value;
			Console.WriteLine(value);
			return value;
		}

		static void GetToken(ref WebClient webClient)
		{
			string value2 = JObject.Parse(Encoding.UTF8.GetString(webClient.UploadData("https://api.twitter.com/1.1/guest/activate.json", new byte[0])))["guest_token"].ToString();
			Console.WriteLine(value2);
			webClient.Headers["x-guest-token"] = value2;
		}

		static string GetUserID(ref WebClient webClient,string path,string userName)
		{
			string text2 = $"https://api.twitter.com/graphql/{path}/UserByScreenName?variables=%7B%22screen_name%22%3A%22{userName}%22%2C%22withHighlightedLabel%22%3Afalse%7D";
			return JObject.Parse(Encoding.UTF8.GetString(webClient.DownloadData(text2)))["data"]["user"]["rest_id"].ToString();
		}

		static Tweet[] GetTweets(ref WebClient webClient,string userId)
		{
			string address = $"https://api.twitter.com/2/timeline/profile/{userId}.json?tweet_mode=extended&simple_quoted_tweet=true";
			string string3 = Encoding.UTF8.GetString(webClient.DownloadData(address));
			var json = JObject.Parse(string3);
			List<Tweet> tweets = new List<Tweet>();
			foreach (var item in json["timeline"]["instructions"][0]["addEntries"]["entries"])
			{
				var entryId = item["entryId"].ToString();
				if (entryId.Contains("tweet"))
				{
					var id = item["sortIndex"].ToString();
					ParseTweet(json, id, out Tweet tweet);
					tweets.Add(tweet);
				}
			}
			return tweets.ToArray();
		}

		static void ParseTweet(JObject json,string tweetId,out Tweet tweet)
		{
			var temp = json["globalObjects"]["tweets"][tweetId] as JObject;
			if (temp != null)
			{
				tweet = new Tweet();
				tweet.ID = tweetId;
				tweet.CreatTime = DateTime.ParseExact(temp["created_at"].ToString(), "ddd MMM dd HH:mm:ss zzz yyyy", CultureInfo.InvariantCulture);
				var isRetweet = temp.ContainsKey("retweeted_status_id_str");
				var userId = temp["user_id_str"].ToString();
				tweet.UserName = json["globalObjects"]["users"][userId]["name"].ToString();
				if (temp.ContainsKey("extended_entities"))
				{
					var extended = temp["extended_entities"] as JObject;
					if (extended.ContainsKey("media"))
					{
						tweet.Media = extended["media"] as JArray;
					}
				}
				if (isRetweet)
				{
					var retweetId = temp["retweeted_status_id_str"].ToString();
					var full_text = temp["full_text"].ToString();
					if (!full_text.StartsWith("RT @")) tweet.Content = full_text;
					ParseTweet(json, retweetId, out Tweet retweet);
					tweet.Retweet = retweet;
				}
				else
				{
					tweet.Content = temp["full_text"].ToString();
					tweet.Content = tweet.Content.Substring(0, temp["display_text_range"][1].ToObject<int>());
					if (temp.ContainsKey("quoted_status_id_str"))
					{
						ParseTweet(json, temp["quoted_status_id_str"].ToString(), out Tweet retweet);
						tweet.Retweet = retweet;
					}
				}
			}
			else tweet = null;
		}
	}

	class Tweet
	{
		public string ID { get; set; }
		public string Content { get; set; }
		public JArray Media { get; set; }
		public DateTime CreatTime { get; set; }
		public string UserName { get; set; }
		public Tweet Retweet { get; set; }
	}
}
